// FileStorageManager.cpp
#include "FileStorageManager.hpp"
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>

FileStorageManager::FileStorageManager(int cameraId, const StoreConfig &config)
    : m_cameraId(cameraId), m_imageQueue(20), m_running(false), m_config(config) {
    m_lastNumberFile = m_config.filePath + "/last_camera_number.txt";
    m_syncFile = m_config.filePath + "/image_time_sync.syn";
    loadLastCameraNumber();
}

FileStorageManager::~FileStorageManager() {
    stop();
    saveLastCameraNumber();
}


void FileStorageManager::initialize(const StoreConfig &config) {
    m_config = config;
}

void FileStorageManager::start() {
    if (!m_running) {
        m_running = true;
        m_storageThread = std::thread(&FileStorageManager::storageLoop, this);
    }
}

void FileStorageManager::stop() {
    if (m_running) {
        m_running = false;
        if (m_storageThread.joinable()) {
            m_storageThread.join();
        }
    }
}

int FileStorageManager::enqueueImage(const FileFrameData &frameData) {
    if (m_config.enable) {
        if (!m_imageQueue.push(frameData)) {
            std::cerr << "Image queue is full for camera " << m_cameraId << std::endl;
            return -1;
        }
    }
    return 0;
}

void FileStorageManager::storageLoop() {
    while (m_running) {
        FileFrameData frameData;
        if (m_imageQueue.wait_for(frameData, 100) == 0) {
            storeImage(frameData);
        }
    }
}

void FileStorageManager::storeImage(const FileFrameData &frameData) {
    std::string filename = generateFilename();
    std::ofstream file(filename, std::ios::binary);
    if (file.is_open()) {
        file.write(reinterpret_cast<const char *>(frameData.data.data()), frameData.data.size());
        file.close();
        std::cout << "Stored image: " << filename << std::endl;

        // 更新同步文件
        std::ofstream syncFile(m_syncFile, std::ios::app);
        if (syncFile.is_open()) {
            // 从完整路径中提取文件名
            size_t lastSlash = filename.find_last_of("/\\");
            std::string baseName = (lastSlash != std::string::npos) ? filename.substr(lastSlash + 1) : filename;

            syncFile << "#" << baseName << "," << frameData.formattedTime << "@\n";
            syncFile.close();
        } else {
            std::cerr << "Failed to open sync file for writing" << std::endl;
        }

        // 增加计数器并保存
        m_lastCameraNumber++;
        saveLastCameraNumber();
    } else {
        std::cerr << "Failed to open file for writing: " << filename << std::endl;
    }
}

std::string FileStorageManager::generateFilename() {
    std::stringstream ss;

#if 0
    ss << m_config.filePath << "/camera_" << m_cameraId << "_";
    ss << formattedTime;
    ss << "_" << std::setfill('0') << std::setw(4) << m_config.pos++ << ".jpg";
#endif

    ss << m_config.filePath << "/camera" << m_lastCameraNumber << ".jpg";
    return ss.str();

}

void FileStorageManager::loadLastCameraNumber() {
    std::ifstream file(m_lastNumberFile);
    if (file.is_open()) {
        file >> m_lastCameraNumber;
        file.close();
    } else {
        m_lastCameraNumber = 0;
    }
}

void FileStorageManager::saveLastCameraNumber() {
    std::ofstream file(m_lastNumberFile);
    if (file.is_open()) {
        file << m_lastCameraNumber;
        file.close();
    } else {
        std::cerr << "Failed to open last number file for writing" << std::endl;
    }
}